package com.ruoyi.core.service.impl;


import com.ruoyi.common.entity.CoreEntity.StockTransactionRecord;
import com.ruoyi.common.entity.CoreEntity.StoreProductStock;
import com.ruoyi.core.mapper.StockTransactionRecordMapper;
import com.ruoyi.core.service.IStockTransactionRecordService;
import com.ruoyi.core.service.IStoreProductStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 库存交易记录 Service 实现
 * 自动维护门店商品库存
 */
@Service
public class StockTransactionRecordServiceImpl implements IStockTransactionRecordService {

    @Autowired
    private StockTransactionRecordMapper stockTransactionRecordMapper;

    @Autowired
    private IStoreProductStockService storeProductStockService;

    /**
     * 查询库存交易记录
     */
    @Override
    public StockTransactionRecord selectStockTransactionRecordById(Long id) {
        return stockTransactionRecordMapper.selectStockTransactionRecordById(id);
    }

    /**
     * 查询库存交易记录列表
     */
    @Override
    public List<StockTransactionRecord> selectStockTransactionRecordList(StockTransactionRecord record) {
        return stockTransactionRecordMapper.selectStockTransactionRecordList(record);
    }

    /**
     * 新增库存交易记录（自动加减库存）
     */
    @Transactional
    @Override
    public int insertStockTransactionRecord(StockTransactionRecord record) {
        handleStockChange(record, true);
        return stockTransactionRecordMapper.insertStockTransactionRecord(record);
    }

    /**
     * 修改库存交易记录（自动调整库存）
     */
    @Transactional
    @Override
    public int updateStockTransactionRecord(StockTransactionRecord record) {
        StockTransactionRecord oldRecord = stockTransactionRecordMapper.selectStockTransactionRecordById(record.getId());
        if (oldRecord == null) {
            throw new RuntimeException("要修改的交易记录不存在");
        }
        // 如果库存相关字段有变化，则先回滚旧库存，再应用新库存
        boolean needAdjustStock =
                !oldRecord.getQuantity().equals(record.getQuantity()) ||
                        !oldRecord.getTransactionType().equals(record.getTransactionType()) ||
                        !oldRecord.getSkuId().equals(record.getSkuId()) ||
                        !oldRecord.getStoreInfoId().equals(record.getStoreInfoId());

        if (needAdjustStock) {
            handleStockChange(oldRecord, false); // 回滚旧库存
            handleStockChange(record, true);    // 应用新库存
        }

        return stockTransactionRecordMapper.updateStockTransactionRecord(record);
    }

    /**
     * 批量删除库存交易记录（自动回滚库存）
     */
    @Transactional
    @Override
    public int deleteStockTransactionRecordByIds(Long[] ids) {
        for (Long id : ids) {
            StockTransactionRecord record = stockTransactionRecordMapper.selectStockTransactionRecordById(id);
            if (record != null) {
                handleStockChange(record, false);
            }
        }
        return stockTransactionRecordMapper.deleteStockTransactionRecordByIds(ids);
    }

    /**
     * 删除单条库存交易记录（自动回滚库存）
     */
    @Transactional
    @Override
    public int deleteStockTransactionRecordById(Long id) {
        StockTransactionRecord record = stockTransactionRecordMapper.selectStockTransactionRecordById(id);
        if (record != null) {
            handleStockChange(record, false);
        }
        return stockTransactionRecordMapper.deleteStockTransactionRecordById(id);
    }

    /**
     * 根据交易类型更新库存
     *
     * @param record 库存交易记录
     * @param isAdd  true 表示新增交易记录，false 表示删除交易记录
     */
    private void handleStockChange(StockTransactionRecord record, boolean isAdd) {
        // 查询当前库存
        StoreProductStock query = new StoreProductStock();
        query.setStoreInfoId(record.getStoreInfoId());
        query.setSkuId(record.getSkuId());
        List<StoreProductStock> stockList = storeProductStockService.selectStoreProductStockList(query);

        StoreProductStock stock = stockList.isEmpty() ? null : stockList.get(0);
        Long qty = record.getQuantity() == null ? 0L : record.getQuantity();

        // 删除交易时，数量方向相反
        if (!isAdd) {
            qty = -qty;
        }

        Long type = record.getTransactionType();

        // 入库类（1采购入库，3退货入库，5调拨入库）
        if (type == 1L || type == 3L || type == 5L) {
            if (stock == null) {
                if (qty < 0) {
                    throw new RuntimeException("库存不足，无法删除该入库记录");
                }
                stock = new StoreProductStock();
                stock.setStoreInfoId(record.getStoreInfoId());
                stock.setSkuId(record.getSkuId());
                stock.setStockQuantity(qty);
                storeProductStockService.insertStoreProductStock(stock);
            } else {
                Long newQty = (stock.getStockQuantity() == null ? 0L : stock.getStockQuantity()) + qty;
                if (newQty < 0) {
                    throw new RuntimeException("库存不足，无法删除该入库记录");
                }
                stock.setStockQuantity(newQty);
                storeProductStockService.updateStoreProductStock(stock);
            }
        }
        // 出库类（2销售出库，4调拨出库）
        else if (type == 2L || type == 4L) {
            if (stock == null) {
                if (qty > 0) {
                    throw new RuntimeException("库存不足，无法进行出库");
                } else {
                    // 删除出库记录 → 库存回加
                    stock = new StoreProductStock();
                    stock.setStoreInfoId(record.getStoreInfoId());
                    stock.setSkuId(record.getSkuId());
                    stock.setStockQuantity(-qty);
                    storeProductStockService.insertStoreProductStock(stock);
                }
            } else {
                Long currentStock = stock.getStockQuantity() == null ? 0L : stock.getStockQuantity();
                if (isAdd) {
                    Long newQty = currentStock - qty;
                    if (newQty < 0) {
                        throw new RuntimeException("库存不足，无法进行出库");
                    }
                    stock.setStockQuantity(newQty);
                } else {
                    // 删除出库记录 → 库存增加
                    stock.setStockQuantity(currentStock + record.getQuantity());
                }
                storeProductStockService.updateStoreProductStock(stock);
            }
        }
        else {
            throw new RuntimeException("未知的交易类型: " + type);
        }
    }
}
